<template>
	<view class="container">


		<!-- 提示文字 -->
		<view class="tip">
			<u-icon name="warning" size="32" color="#f9ae3d" style="margin-right: 10rpx;"></u-icon>
			<text>请选择一张图片</text>
		</view>

		<!-- 图片选择区域 -->
		<view class="image-selector">
			<view class="image-grid">
				<view v-for="(image, index) in imageList" :key="index" class="image-box" @click="selectImage(index)"
					:class="{selected: selectedImages.includes(index)}">
					<image class="image-preview" :src="image.fullUrl" mode="aspectFill" @error="onImageError">
					</image>
					<view class="checkbox">
						<u-icon name="checkmark" size="24" color="#ffffff"
							v-if="selectedImages.includes(index)"></u-icon>
					</view>
				</view>
			</view>
		</view>

		<!-- 立即分析按钮 -->
		<view class="action-btn">
			<u-button type="primary" shape="circle" @click="analyzeImages" :disabled="selectedImages.length === 0">
				立即分析
			</u-button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				baseURL: this.$baseURL,
				selectedImages: [],
				imageList: [{
						path: '/profile/upload/2025/05/10/image1_20250507094721A018_20250510150128A024.jpg'
					},
					{
						path: '/profile/upload/2025/05/10/image2_20250507094842A019_20250510150137A025.jpg'
					},
					{
						path: '/profile/upload/2025/05/10/image3_20250507094937A020_20250510150144A026.jpg'
					},
					{
						path: '/profile/upload/2025/05/10/image4_20250507095002A021_20250510150157A027.jpg'
					}
				],
				fullUrl: [],
				query: `你是一位优秀的心理专家，这个图是一个女生的摄影作品，请你根据这个摄影作品给我一个对这个女生的心理评价和对应的情绪分数。要给予他积极的情绪反馈，你需要返回给我一个["72","31","56","66","42","83"]这样的数组,这几个数据是对['高兴','充实','伤心','孤独','迷茫','纠结']这几个情绪的评分，总分一百分，然后在给我对这个女孩的情绪评价，例如："这张照片看起来充满活力和热情。她可能在此时节心情愉悦，因为春天代表新生命、希望和追求。"`,
				selectUrl: '',
				usedTime: null,
				startTime: null
			};
		},
		created() {
			this.imageList = this.imageList.map(image => {
				return {
					...image,
					fullUrl: this.getImageUrl(image.path)
				};
			});
		},
		onReady() {
			//开始计时
			this.startTime = Date.now()
		},
		methods: {
			selectImage(index) {
				// 如果当前已选中的是 index，则取消选择（变成空选）
				if (this.selectedImages[0] === index) {
					this.selectedImages = [];
				} else {
					// 否则只选中当前 index，其他全部取消
					this.selectedImages = [index];
				}
			},
			getImageUrl(path) {
				if (!this.baseURL) {
					console.error('baseURL未定义');
					return path; // 降级处理
				}

				const base = this.baseURL.endsWith('/') ?
					this.baseURL.slice(0, -1) :
					this.baseURL;

				const imagePath = path.startsWith('/') ? path : `/${path}`;

				this.fullUrl = `${base}${imagePath}`;
				console.log('Generated image URL:', this.fullUrl);
				return this.fullUrl;
			},

			analyzeImages() {
				if (this.selectedImages.length === 0) {
					uni.showToast({
						title: '请先选择图片',
						icon: 'none'
					});
					return;
				}
				const selectedPaths = this.selectedImages.map(index => this.imageList[index].path);
				this.selectUrl = this.baseURL + selectedPaths
				console.log("提交路径：", this.selectUrl);

				if (this.startTime) {
					console.log('111')
					const startTime1 = (typeof this.startTime === 'number' && this.startTime < 1e12) ?
						this.startTime * 1000 :
						this.startTime;
					const endTime = Date.now();
					let durationSeconds = Math.floor((endTime - startTime1) / 1000);
					if (durationSeconds < 0 || isNaN(durationSeconds)) durationSeconds = 0;
					this.usedTime = this.formatDuration(durationSeconds);
				} else {
					console.log(this.startTime)
					console.log('222')
					this.usedTime = '未记录';
					console.log('⚠️ startTime 获取失败');
				}

				uni.navigateTo({
					url: '/pages/psychologyModel/drawingAnalysis/drawing/drawingResult',
					success: (res) => {
						// 通过 eventChannel 向目标页面传参
						res.eventChannel.emit('result', {
							aiUrl: this.selectUrl,
							usedTime: this.usedTime,
							query: this.query
						});
					}
				});
			},

			onImageError(event) {
				console.error('图片加载失败:', event);
			},
			formatDuration(seconds) {
				// 把秒数格式化成几分几秒
				const m = Math.floor(seconds / 60)
				const s = seconds % 60
				return `${m}分${s}秒`
			}
		}
	};
</script>

<style lang="scss" scoped>
	.container {
		padding: 0;
		background-color: #fff;
		min-height: 100vh;
		display: flex;
		flex-direction: column;
	}

	.custom-nav-bar {
		padding: 20rpx 30rpx;
		background-color: rgb(248, 248, 248);
		color: white;
		text-align: center;
		padding-top: var(--status-bar-height);
		display: flex;
		align-items: center;
		position: relative;
	}

	.back-icon {
		margin-top: 25rpx;
		position: absolute;
		left: 20rpx;
		top: calc(var(--status-bar-height) + 20rpx);
		z-index: 10;
	}

	.title-container {
		flex: 1;
		text-align: center;
	}

	.custom-nav-bar .title {
		margin-top: 30rpx;
		font-size: 35rpx;
		font-weight: bold;
		display: block;
		color: #000000;
	}

	.custom-nav-bar .subtitle {
		font-size: 25rpx;
		display: block;
		color: #000000;
	}

	.tip {
		margin-top: 5rpx;
		padding: 20rpx;
		background-color: #f8f8f8;
		border-radius: 12rpx;
		display: flex;
		align-items: center;
		color: #666;
		font-size: 28rpx;
	}

	.image-selector {
		margin: 30rpx;
		padding: 20rpx;
		background-color: #fafafa;
		border-radius: 12rpx;
	}

	.hint-text {
		display: block;
		font-size: 24rpx;
		color: #999;
		text-align: center;
		margin-bottom: 10rpx;
	}

	.image-grid {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		margin-top: 30rpx;
	}

	.image-box {
		width: 48%;
		height: 200rpx;
		margin-bottom: 20rpx;
		border-radius: 12rpx;
		position: relative;
		overflow: hidden;
		border: 2rpx solid #e4e7ed;

		&.selected {
			border-color: #1296db;
		}
	}

	.image-preview {
		width: 100%;
		height: 100%;
		background-color: #f5f5f5;
	}

	.checkbox {
		position: absolute;
		right: 10rpx;
		top: 10rpx;
		width: 40rpx;
		height: 40rpx;
		background-color: rgba(18, 150, 219, 0.8);
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.action-btn {
		margin: 40rpx 30rpx;
		padding: 0 60rpx;
	}
</style>